<?php
require __DIR__ . '/utils.php';
$c = cfg(); $pdo = db();

$ip       = client_ip();
$ip_store = $c['anonymize_ip'] ? anonymize_ip($ip) : $ip;

$ua       = $_SERVER['HTTP_USER_AGENT'] ?? '';
$ref      = $_SERVER['HTTP_REFERER'] ?? '';
$lang     = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
$path     = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$method   = $_SERVER['REQUEST_METHOD'] ?? 'GET';

$consent  = isset($_REQUEST['consent']) && $_REQUEST['consent'] == '1';
$ua_hash  = hash_str($ua);
$ref_hash = $ref ? hash_str($ref) : null;
$ua_raw   = ($consent && $c['allow_raw_ua_on_consent']) ? $ua : null;

// 获取GPS数据
$gps_lat = $gps_lng = $gps_acc = null;
if ($method === 'POST') {
    $rawData = file_get_contents('php://input');
    if ($rawData) {
        $jsonData = json_decode($rawData, true);
        if ($jsonData && isset($jsonData['gps']) && $jsonData['gps']) {
            $gpsData = $jsonData['gps'];
            $gps_lat = isset($gpsData['lat']) ? round($gpsData['lat'], 6) : null;
            $gps_lng = isset($gpsData['lng']) ? round($gpsData['lng'], 6) : null;
            $gps_acc = isset($gpsData['accuracy']) ? (int)$gpsData['accuracy'] : null;
        }
    }
}

$stmt = $pdo->prepare("
INSERT INTO logs (ip_anonymized, ua_hash, ua_raw, ref_hash, path, method, accept_lang, consent, gps_lat, gps_lng, gps_accuracy)
VALUES (:ip, :uah, :uar, :refh, :path, :method, :lang, :consent, :lat, :lng, :acc)
");
$stmt->execute([
    ':ip'     => $ip_store,
    ':uah'    => $ua_hash,
    ':uar'    => $ua_raw,
    ':refh'   => $ref_hash,
    ':path'   => $path,
    ':method' => $method,
    ':lang'   => $lang,
    ':consent'=> $consent ? 1 : 0,
    ':lat'    => $gps_lat,
    ':lng'    => $gps_lng,
    ':acc'    => $gps_acc
]);

// 返回 204 以适配 fetch/像素请求
http_response_code(204);
header('Cache-Control: no-store');
